﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.IO;

namespace BulldogCMS.Core.Storage.Providers
{
    public class LocalStorageUniqueIdentifierProvider : IUniqueIdentifierProvider
    {
        private static string STORAGE_META_FILENAME = "StorageMeta.xml";

        private string StoragePath
        {
            get;
            set;
        }

        public long GetNextUniqueID()
        {
            string fileName = Path.Combine(this.StoragePath, STORAGE_META_FILENAME);
            XDocument xDoc = XDocument.Load(fileName);
            long lastID = xDoc.Root.Element("generator").GetAttributeValue<long>("lastID");
            long step = xDoc.Root.Element("generator").GetAttributeValue<long>("step");
            long newID = lastID + step;
            xDoc.Root.Element("generator").SetAttributeValue("lastID", newID);
            xDoc.Save(fileName);
            return newID;
        }

        public void SetParameter(string name, string value)
        {
            if ("storagePath".Equals(name, StringComparison.InvariantCultureIgnoreCase))
            {
                if (value.StartsWith("~/"))
                {
                    this.StoragePath = HttpContext.Current.Server.MapPath(value);
                }
                else
                {
                    this.StoragePath = value;
                }
            }
        }

    }
}